package cn.xw.commons.core.utils.springRedisUtils;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 基于Spring的Redis工具类的配置
 *
 * @author Anhui AntLaddie <a href="https://www.cnblogs.com/antLaddie/">(博客园蚂蚁小哥)</a>
 * @version 1.0
 **/
@Configuration
public class RedisConfig {

    /***
     * 配置我们自定义的Redis模板，可以对对象序列化存入redis
     * @param redisConnectionFactory  redis工厂
     * @return 自定义的Redis存储模板（改变原生的值序列化看不懂问题）
     */
    @Bean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        //配置我们自己的Redis模板，一般我们的key都为String，值为Object
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //设置Redis连接工厂
        template.setConnectionFactory(redisConnectionFactory);

        //配置JSON序列化方式
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer =
                new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);  已过时
        om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        //配置String序列化方式
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        //注意：下面配置是关于key使用String序列化，而value则使用json(jackson)来序列化,如果key存放对象则会报错
        //key采用String序列化方式
        template.setKeySerializer(stringRedisSerializer);
        //value采用String序列化方式
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //hash的Key采用String序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        //hash的value采用String序列化方式
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}
